﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.StandardBomAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class CreateStandardBomCommand : StandardBomEditRequestDto, IRequest<Result<StandardBomInfoResponseDto>>
    {
    }

    public class CreateStandardBomCommandHandler :
        IRequestHandler<CreateStandardBomCommand, Result<StandardBomInfoResponseDto>>
    {
        private readonly IStandardBomRepository _standardBomRepository;
        private readonly IMapper _mapper;

        public CreateStandardBomCommandHandler(IStandardBomRepository standardBomRepository,
            IMapper mapper)
        {
            _standardBomRepository = standardBomRepository;
            _mapper = mapper;
        }

        public async Task<Result<StandardBomInfoResponseDto>> Handle(CreateStandardBomCommand request,
            CancellationToken cancellationToken)
        {
            var standardBom = new StandardBom(request.Code, request.Name, request.Version,
                request.Contract, request.Material.Id, request.Material.Code, request.Material.Name,
                request.Quality,
                request.Description);

            _standardBomRepository.Add(standardBom);

            if (request.Items != null)
            {
                foreach (var item in request.Items)
                {
                    standardBom.AddItem(item.MaterialId, item.MaterialCode, item.MaterialName, item.Quality,
                        item.LossRate);
                }
            }

            await _standardBomRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<StandardBomInfoResponseDto>.SuccessAsync(
                _mapper.Map<StandardBomInfoResponseDto>(standardBom));
        }
    }
}